package cn.gson.school.controller.zhaosheng;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.gson.school.dao.xitong.DeptSerchDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.dao.zhaosheng.FollowupDao;
import cn.gson.school.dao.zhaosheng.InputStudentDao;
import cn.gson.school.dao.zhaosheng.SigninggrecordDao;
import cn.gson.school.dao.zhaosheng.TranferassistDao;
import cn.gson.school.entity.xitong.DeptEntity;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.entity.zhaosheng.FollowupEntity;
import cn.gson.school.entity.zhaosheng.InputStudentEntity;
import cn.gson.school.entity.zhaosheng.SigningrecordEntity;
import cn.gson.school.entity.zhaosheng.TranferassistEntity;
import cn.gson.school.mappers.zhaosheng.InputStudentMapper;

/**
 * 录入学生信息Controller
 */
@Controller
@RequestMapping("/zs-inputstuinfo")
public class InputStudentController {
	@Autowired
	private InputStudentMapper inputStudentMapper;

	@Autowired
	private InputStudentDao inputStudentDao;

	@Autowired
	private TranferassistDao tranferassistDao;

	@Autowired
	private SigninggrecordDao signingrecordDao;

	@Autowired
	private FollowupDao followupDao;

	@Autowired
	private UserInfoDao userInfoDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private DeptSerchDao deptDao;

	@RequestMapping("list")
	@ResponseBody
	public JSONObject index(InputStudentEntity inputStuEntity,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		System.out.println("录入学生" + inputStuEntity);
		PageHelper.startPage(pageNum, pageSize);
		Page<InputStudentEntity> pageData = (Page<InputStudentEntity>) inputStudentMapper.list(inputStuEntity);
		JSONObject obj = new JSONObject();
		obj.put("total", pageData.getTotal());
		obj.put("rows", pageData.getResult());
		return obj;
	}

	@GetMapping("delete/{id}")
	@ResponseBody
	public JSONObject delete(@PathVariable("id") Long id) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		InputStudentEntity u;
		if (id != null && (u = inputStudentDao.findOne(id)) != null) {
			inputStudentDao.delete(u);
			obj.put("success", true);
		} else {
			obj.put("message", "此用户不存在！");
		}
		return obj;
	}

	/**
	 * 表单
	 */
	@GetMapping({ "zs-addstuinfo", "zs-addstuinfo/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			InputStudentEntity u = inputStudentDao.findOne(id);
			if (u != null) {
				model.addAttribute("inputStuEntity", u);
			}
		}
		return "zhaosheng/zs-addstuinfo";
	}

	/**
	 * 分配咨询师
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("zs-stuinfo-distribution/{id}")
	public String disform(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			InputStudentEntity u = inputStudentDao.findOne(id);
			DeptEntity dept = deptDao.findOne(3L);
			List<UserInfoEntity> allUserName = userInfoDao.findByDept(dept);
			if (u != null) {
				model.addAttribute("inputStuEntity", u);
				model.addAttribute("userInfoEntity", allUserName);
			}
		}
		return "zhaosheng/zs-stuinfo-distribution";
	}

	/**
	 * 添加分配信息
	 * 
	 * @throws ParseException
	 */
	@PostMapping("savefollow")
	@ResponseBody
	public Map<String, Object> savefollow(@Valid FollowupEntity followEntity, BindingResult br,
			HttpServletRequest request) throws ParseException {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "信息校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			/* 添加，编辑所需获取的信息 */
			String inputstuname = request.getParameter("inputstuName");// 获取学生姓名
			String usersName = request.getParameter("usersName");// 获取分配的咨询师
			UserInfoEntity userInfoEntity = userInfoDao.findByUserName(usersName);// 找到分配的咨询师
			if (followEntity.getFollowId() == null) {
				if (inputstuname == null) {
					obj.put("message", "学生姓名不能为空！");
					return obj;
				}
				InputStudentEntity student = inputStudentDao.findByInputStuName(inputstuname);
				followEntity.setInputStuName(student);
				followEntity.setUserinfoName(userInfoEntity);// 设置分配咨询师
				followEntity.setFollowTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
				followEntity.setFollowStuStatus(-1);
				student.setStatus(1);// 已分配后修改学生状态
			} else {
				// 编辑的时的两种情况
				// 1、有信息，更新信息
				InputStudentEntity student = inputStudentDao.findByInputStuName(inputstuname);
				followEntity.setInputStuName(student);
				followEntity.setUserinfoName(userInfoEntity);// 设置分配咨询师
				followEntity.setFollowTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
				followEntity.setFollowStuStatus(0);
				student.setStatus(1);// 已分配后修改学生状态
			}
			followupDao.save(followEntity);
			obj.put("success", true);
		}
		return obj;
	}

	/**
	 * 添加学员信息
	 * 
	 * @param inputStuEntity
	 * @param br
	 * @return
	 */
	@PostMapping("save")
	@ResponseBody
	public JSONObject save(@Valid InputStudentEntity inputStuEntity, BindingResult br, HttpServletRequest request) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "信息校验失败！你输入的信息格式可能有误！");
			obj.put("erros", br.getFieldErrors());
		} else {
			Long userId = Long.parseLong(request.getParameter("userid"));
			UserInfoEntity user = userInfoDao.findOne(userId);
			System.out.println(inputStuEntity.getInputstuId());
			if (inputStuEntity.getInputstuId() == null) {
				if (inputStuEntity.getInputStuName() == null) {
					obj.put("message", "学生姓名不能为空！");
					return obj;
				} else if (inputStuEntity.getPhone() == null) {
					obj.put("message", "电话号码不能为空！");
					return obj;
				} else if (inputStuEntity.getAddress() == null) {
					obj.put("message", "地址不能为空！");
					return obj;
				} else if (inputStuEntity.getEmail() == null) {
					obj.put("message", "邮箱不能为空！");
					return obj;
				} else if (inputStuEntity.getAge() <= 0 || inputStuEntity.getAge() > 100) {
					obj.put("message", "年龄长度不能小于等于0或大于100！");
					return obj;
				} else if (inputStuEntity.getPhone().length() < 11) {
					obj.put("message", "手机号码必须是11位！");
					return obj;
				}
				inputStuEntity.setInputStuName(inputStuEntity.getInputStuName());
				inputStuEntity.setGender(inputStuEntity.getGender());
				inputStuEntity.setPhone(inputStuEntity.getPhone());
				inputStuEntity.setAddress(inputStuEntity.getAddress());
				inputStuEntity.setDegree(inputStuEntity.getDegree());
				inputStuEntity.setAge(inputStuEntity.getAge());
				inputStuEntity.setInterest(inputStuEntity.getInterest());
				inputStuEntity.setRemark(inputStuEntity.getRemark());
				inputStuEntity.setEmail(inputStuEntity.getEmail());
				inputStuEntity.setUserinfoId(user);
				inputStuEntity.setStatus(0);
			} else {
				// 编辑的时的两种情况
				// 1、有信息，更新信息
				System.out.println(inputStuEntity.getInputStuName());
				inputStuEntity.setInputStuName(inputStuEntity.getInputStuName());
				inputStuEntity.setGender(inputStuEntity.getGender());
				inputStuEntity.setPhone(inputStuEntity.getPhone());
				inputStuEntity.setAddress(inputStuEntity.getAddress());
				inputStuEntity.setDegree(inputStuEntity.getDegree());
				inputStuEntity.setAge(inputStuEntity.getAge());
				inputStuEntity.setInterest(inputStuEntity.getInterest());
				inputStuEntity.setRemark(inputStuEntity.getRemark());
				inputStuEntity.setEmail(inputStuEntity.getEmail());
				inputStuEntity.setUserinfoId(user);
				inputStuEntity.setStatus(0);
			}
			inputStudentDao.save(inputStuEntity);
			obj.put("success", true);
		}
		return obj;
	}

	/**
	 * 表单
	 */
	@GetMapping({ "zs-transferass-add", "zs-transferass-add/{id}" })
	public String addTranform(@PathVariable(name = "id", required = false) Long id, Model model) {
		System.out.println("学生id：" + id);
		if (id != null) {
			InputStudentEntity stu = inputStudentDao.findOne(id);
			DeptEntity dept = deptDao.findOne(3L);
			List<UserInfoEntity> allUserName = userInfoDao.findByDept(dept);
			if (stu != null) {
				TranferassistEntity tran1 = tranferassistDao.findByInputstuName(stu);
				System.out.println("当前学生是否有移交记录：" + tran1);
				if (tran1 != null) {
					model.addAttribute("tranferassistEntity", tran1);
					model.addAttribute("consultant", allUserName);
				} else {
					model.addAttribute("inputStuEntity", stu);
					model.addAttribute("consultant", allUserName);
				}
			}
		}
		return "zhaosheng/zs-transferass-add";
	}

	/**
	 * 表单
	 */
	@GetMapping({ "zs-add-qianyue", "zs-add-qianyue/{id}" })
	public String addSign(@PathVariable(name = "id", required = false) Long id, Model model) {
		System.out.println("学生id：" + id);
		if (id != null) {
			InputStudentEntity stu = inputStudentDao.findOne(id);
			DeptEntity dept = deptDao.findOne(3L);
			List<UserInfoEntity> allUserName = userInfoDao.findByDept(dept);
			if (stu != null) {
				SigningrecordEntity tran1 = signingrecordDao.findByInputstuId(stu);
				System.out.println("当前学生是否有移交记录：" + tran1);
				if (tran1 != null) {
					model.addAttribute("signingrecordEntity", tran1);
					model.addAttribute("consultant", allUserName);
				} else {
					model.addAttribute("inputStuEntity", stu);
					model.addAttribute("consultant", allUserName);
				}
			}
		}
		return "zhaosheng/zs-add-qianyue";
	}

	/**
	 * 查询学员是否签约
	 */
	@GetMapping("sign/{id}")
	@ResponseBody
	public JSONObject sign(@PathVariable("id") Long id) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		InputStudentEntity u;
		if (id != null && (u = inputStudentDao.findOne(id)) != null) {
			SigningrecordEntity tran1 = signingrecordDao.findByInputstuId(u);
			System.out.println("当前学生是否有移交记录：" + tran1);
			if (tran1 == null) {
				obj.put("success", true);
			}else {
				obj.put("message", "该学员已签约！不能再签约了！");
			}
		} else {
			obj.put("message", "该学员不存在！");
		}
		return obj;
	}
}
